package Work;

import Work.Product;
import Work.ProductService;
import Work.ProductSorters;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ConsoleShop {
    private final ProductService productService = new ProductService();
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    browseProducts(null); // 无Comparator：默认排序
                    break;
                case 2:
                    showSortedProducts(); // 自定义排序浏览
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 5:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    // 显示主菜单（新增“自定义排序浏览商品”选项）
    private void showMenu() {
        System.out.println("\n===== 欢迎来到商城 =====");
        System.out.println("1. 浏览所有商品（默认排序）");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 查看购物车");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    // 自定义排序浏览的子菜单
    private void showSortedProducts() {
        System.out.println("\n--- 排序方式选择 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.print("请选择排序方式: ");
        int sortChoice = scanner.nextInt();
        scanner.nextLine();

        // 根据选择获取对应的Comparator
        switch (sortChoice) {
            case 1:
                browseProducts(ProductSorters.BY_PRICE_ASC);
                break;
            case 2:
                browseProducts(ProductSorters.BY_PRICE_DESC);
                break;
            case 3:
                browseProducts(ProductSorters.BY_STOCK_DESC);
                break;
            default:
                System.out.println("无效的排序选项，默认按ID排序");
                browseProducts(null);
        }
    }

    // 改造后的浏览商品方法：支持传入Comparator（null则默认排序）
    private void browseProducts(java.util.Comparator<Product> comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
            return;
        }

        // 排序逻辑：传入Comparator则用其排序，否则用自然排序
        if (comparator != null) {
            products.sort(comparator);
        } else {
            Collections.sort(products); // 调用Product的compareTo（按ID排序）
        }

        products.forEach(System.out::println);
    }

    // 原有功能：添加购物车、查看购物车（保持不变）
    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine();
        if (quantity <= 0 || quantity > product.getStock()) {
            System.out.println(quantity <= 0 ? "错误：购买数量必须为正数！" : "错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            if (product != null) {
                double subtotal = product.getPrice() * entry.getValue();
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), entry.getValue(), subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }
    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}